package com.jn.zhinongbao.adapter.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.bean.ChatRoom;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 聊天室列表适配器
 */
public class ChatRoomAdapter extends RecyclerView.Adapter<ChatRoomAdapter.ViewHolder> {

    private Context context;
    private List<ChatRoom> chatRooms;
    private int currentUserId;
    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(ChatRoom chatRoom);
        void onItemLongClick(ChatRoom chatRoom);
    }

    public ChatRoomAdapter(Context context, List<ChatRoom> chatRooms, int currentUserId) {
        this.context = context;
        this.chatRooms = chatRooms;
        this.currentUserId = currentUserId;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_chat_room, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ChatRoom chatRoom = chatRooms.get(position);
        holder.bind(chatRoom);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(chatRoom);
            }
        });

        holder.itemView.setOnLongClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemLongClick(chatRoom);
            }
            return true;
        });
    }

    @Override
    public int getItemCount() {
        return chatRooms != null ? chatRooms.size() : 0;
    }

    public void updateData(List<ChatRoom> newChatRooms) {
        this.chatRooms = newChatRooms;
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvChatName;
        private TextView tvLastMessage;
        private TextView tvLastTime;
        private TextView tvUnreadCount;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvChatName = itemView.findViewById(R.id.tv_chat_name);
            tvLastMessage = itemView.findViewById(R.id.tv_last_message);
            tvLastTime = itemView.findViewById(R.id.tv_last_time);
            tvUnreadCount = itemView.findViewById(R.id.tv_unread_count);
        }

        public void bind(ChatRoom chatRoom) {
            // 显示对方的名称
            tvChatName.setText(chatRoom.getOtherUserName(currentUserId));

            // 显示最后一条消息
            String lastMessage = chatRoom.getLastMessage();
            if (lastMessage != null && !lastMessage.isEmpty()) {
                tvLastMessage.setText(lastMessage);
            } else {
                tvLastMessage.setText("暂无消息");
            }

            // 显示最后消息时间
            String lastTime = formatTime(chatRoom.getLastMessageTime());
            tvLastTime.setText(lastTime);

            // 显示未读消息数量
            int unreadCount = chatRoom.getUnreadCount();
            if (unreadCount > 0) {
                tvUnreadCount.setVisibility(View.VISIBLE);
                if (unreadCount > 99) {
                    tvUnreadCount.setText("99+");
                } else {
                    tvUnreadCount.setText(String.valueOf(unreadCount));
                }
            } else {
                tvUnreadCount.setVisibility(View.GONE);
            }
        }

        /**
         * 格式化时间显示
         * @param timeString 时间字符串
         * @return 格式化后的时间
         */
        private String formatTime(String timeString) {
            try {
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date messageTime = inputFormat.parse(timeString);
                Date now = new Date();
                
                // 计算时间差
                long diff = now.getTime() - messageTime.getTime();
                long diffDays = diff / (24 * 60 * 60 * 1000);
                
                if (diffDays == 0) {
                    // 今天显示时分
                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
                    return timeFormat.format(messageTime);
                } else if (diffDays == 1) {
                    // 昨天
                    return "昨天";
                } else if (diffDays < 7) {
                    // 一周内显示周几
                    SimpleDateFormat weekFormat = new SimpleDateFormat("E", Locale.getDefault());
                    return weekFormat.format(messageTime);
                } else {
                    // 超过一周显示月日
                    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd", Locale.getDefault());
                    return dateFormat.format(messageTime);
                }
            } catch (Exception e) {
                return timeString;
            }
        }
    }
} 